<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商家名称" prop="merName">
        <el-input
            v-model="queryParams.merName"
            placeholder="请输入商家名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="法人" prop="blisLegal">
        <el-input
            v-model="queryParams.blisLegal"
            placeholder="请输入法人"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商家类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择商家类型" clearable>
          <el-option
              v-for="dict in t_mer_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商家性质" prop="merKind">
        <el-select v-model="queryParams.merKind" placeholder="请选择商家性质" clearable>
          <el-option
              v-for="dict in t_mer_kind"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:tmeraudit:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tmerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="商家名称" align="center" prop="merName" width="200"/>
      <el-table-column label="商家类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="t_mer_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="商家性质" align="center" prop="merKind">
        <template #default="scope">
          <dict-tag :options="t_mer_kind" :value="scope.row.merKind"/>
        </template>
      </el-table-column>
      <el-table-column label="签约时间" align="center" prop="contSignTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.contSignTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="contStartTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.contStartTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="contEndTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.contEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="t_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row, scope.index)"
                     v-hasPermi="['system:tmer:terminate']">查看
          </el-button>
          <el-button link type="primary" icon="Checked" @click="handleAudit(scope.row)"
                     v-hasPermi="['system:tmeraudit:audit']">审核
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 商家审核 -->
    <el-dialog :title="title" v-model="open" width="650px" append-to-body>
      <el-form ref="tmerRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="审核意见" prop="auditStatus">
              <el-radio-group v-model="form.auditStatus">
                <el-radio
                    v-for="dict in t_audit"
                    :key="dict.value"
                    :label="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="审核原因" prop="statusReason">
              <el-input v-model="form.statusReason" placeholder="请输入审核原因"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="form.type!==3">
            <el-form-item label="签约时间" prop="contSignTime">
              <el-date-picker 
                :clearable="false"  
                v-model="form.contSignTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择合约签约时间"
                @change="handleSignTime"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="form.type!==3">
            <el-form-item label="签约起止" prop="contStartTime">
              <el-date-picker
                  :clearable="false"
                  v-model="contTimeRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                  @change="handleContTimeChange"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="form.type!==3">
            <el-form-item label="合约期限" prop="contLimit">
              <el-input v-model="form.contLimit" placeholder="请输入合约期限" :readonly="true"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="auditSubmitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看商家详情 -->
    <el-dialog title="商家详情" v-model="viewOpen" width="1000px" append-to-body>
      <el-form ref="packageRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商家名称:" prop="merName" label-width="auto">
              {{  form.merName  }}
              <!-- <el-input v-model="form.merName" placeholder="请输入" :disabled="true"/> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商家描述:" prop="merDesc" label-width="auto">
              <!-- <el-input v-model="form.merDesc" placeholder="暂无" :disabled="true"/> -->
              {{  form.merDesc }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商家类型" prop="type" label-width="auto">
              <el-select v-model="form.type" placeholder="请选择商家类型" :disabled="true">
                <el-option
                    v-for="dict in t_mer_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商家性质" prop="merKind" label-width="auto">
              <el-select v-model="form.merKind" placeholder="请选择商家性质" :disabled="true">
                <el-option
                    v-for="dict in t_mer_kind"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="form.merKind === 1">
            <el-form-item label="身份证号" prop="idCardNo" label-width="auto">
              <el-input v-model="form.idCardNo" placeholder="请输入身份证号" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="form.merKind === 1">
            <el-form-item label="身份证正面" prop="idCardFrontPic" label-width="auto">
              <image-preview :src="form.idCardFrontPic" :width="150" :height="150"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.merKind === 1">
            <el-form-item label="身份证反面" prop="idCardBackPic" label-width="auto">
              <image-preview :src="form.idCardBackPic" :width="150" :height="150"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
<!--          <el-col :span="12" v-if="form.merKind === 2">-->
<!--            <el-form-item label="营业执照" prop="blisNo" label-width="auto">-->
<!--              <el-input v-model="form.blisNo" placeholder="暂无" :disabled="true"/>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="12" v-if="form.merKind === 2">
            <el-form-item label="法人" prop="blisLegal" label-width="auto">
              <el-input v-model="form.blisLegal" placeholder="请输入法人" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="合同信息" prop="contPic">
              <image-preview :src-list="form.contPic" :width="150" :height="150"/>
            </el-form-item>
          </el-col>
<!--          <el-col :span="12" v-if="form.merKind === 2">-->
<!--            <el-form-item label="营业执照" prop="blisPic">-->
<!--              <image-preview :src="form.blisPic" :width="150" :height="150"/>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="签约时间" prop="contSignTime">
              {{ form.contSignTime }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="签约起止" prop="contStartTime">
              {{ form.contStartTime }} - {{ form.contEndTime }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合约期限" prop="contLimit">
              <el-input v-model="form.contLimit" placeholder="暂无" :readonly="true" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactName">
              <el-input v-model="form.contactName" placeholder="暂无" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系邮箱" prop="contactEmail">
              <el-input v-model="form.contactEmail" placeholder="暂无" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系地址" prop="contactAddr">
              <el-input v-model="form.contactAddr" placeholder="暂无" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行名称" prop="bankName">
              {{ form.bankName }}
              <!-- <el-input v-model="form.bankName" placeholder="请输入银行名称" :disabled="true"/> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开户行" prop="bankOpenName">
              {{ form.bankOpenName }}
              <!-- <el-input v-model="form.bankOpenName" placeholder="请输入开户行名称" :disabled="true"/> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行卡号" prop="bankCardNo">
              <el-input v-model="form.bankCardNo" placeholder="请输入银行卡号" :disabled="true"/>
              <!-- {{ form.bankCardNo }} -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="绑定手机" prop="bankCardPhone">
              <el-input v-model="form.bankCardPhone" placeholder="请输入银行绑定手机号" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type!==3">
            <el-form-item label="经销商">
              {{ form.parName }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Tmer">
import {listTmer, getTmer, updateStatus} from "@/api/system/tmer";
import {ref} from "vue";
import {ElMessage} from "element-plus";

const {proxy} = getCurrentInstance();
const {t_mer_type, t_status, t_mer_kind, t_audit} = proxy.useDict('t_mer_type', 't_status', 't_mer_kind', 't_audit');

const tmerList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const contTimeRange = ref([]);
const viewOpen = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    merName: undefined,
    merDesc: undefined,
    type: undefined,
    merKind: undefined,
    idCardNo: undefined,
    idCardName: undefined,
    idCardFrontPic: undefined,
    idCardBackPic: undefined,
    blisNo: undefined,
    blisLegal: undefined,
    blisPic: undefined,
    contSignTime: undefined,
    contStartTime: undefined,
    contEndTime: undefined,
    contLimit: undefined,
    contactName: undefined,
    contactEmail: undefined,
    contactAddr: undefined,
    bankName: undefined,
    bankOpenName: undefined,
    bankCardNo: undefined,
    bankCardPhone: undefined,
    status: '01',
    statusReason: undefined,
    auditTime: undefined,
    auditor: undefined,
    ext1: undefined,
    ext2: undefined,
    ext3: undefined,
  },
  rules: {
    auditStatus: [
      {required: true, message: "审核意见不能为空", trigger: "blur"}
    ],
    statusReason: [
      {required: true, message: "审核原因不能为空", trigger: "blur"}
    ],
    contSignTime: [
      {required: true, message: "请选择签约时间！", trigger: "change"},
    ],
    contStartTime: [
      {required: true, message: "请选择签约起止时间！", trigger: "change"},
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询商家列表列表 */
function getList() {
  loading.value = true;
  listTmer(queryParams.value).then(response => {
    tmerList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    merId: undefined,
    merName: undefined,
    merDesc: undefined,
    type: undefined,
    merKind: undefined,
    idCardNo: undefined,
    idCardName: undefined,
    idCardFrontPic: undefined,
    idCardBackPic: undefined,
    blisNo: undefined,
    blisLegal: undefined,
    blisPic: undefined,
    contSignTime: undefined,
    contStartTime: undefined,
    contEndTime: undefined,
    contLimit: undefined,
    contactName: undefined,
    contactEmail: undefined,
    contactAddr: undefined,
    bankName: undefined,
    bankOpenName: undefined,
    bankCardNo: undefined,
    bankCardPhone: undefined,
    status: '01',
    statusReason: undefined,
    auditTime: undefined,
    auditor: undefined,
    ext1: undefined,
    ext2: undefined,
    ext3: undefined,
    state: undefined,
    createTime: undefined,
    creator: undefined,
    modifyTime: undefined,
    modifier: undefined
  };
  proxy.resetForm("tmerRef");
  contTimeRange.value = [];
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.merId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/tmer/export', {
    ...queryParams.value
  }, `tmer_${new Date().getTime()}.xlsx`)
}

/** 审核操作 */
function handleAudit(row) {
  reset();
  form.value = row;
  form.value.statusReason = '';
  contTimeRange.value = [row.contStartTime, row.contEndTime];
  open.value = true;
  title.value = "审核商家";
}

function auditSubmitForm(row) {
  proxy.$refs["tmerRef"].validate(valid => {
    if (valid) {
      if (form.value.merId != null) {
        form.value.status = form.value.auditStatus;
        updateStatus(form.value).then(response => {
          proxy.$modal.msgSuccess("审核成功");
          open.value = false;
          getList();
        });
      } else {

      }
    }
  });
}
/** 详细按钮操作 */
function handleView(row) {
  const _merId = row.merId || ids.value
  getTmer(_merId).then(response => {
    form.value = response.data;
    if(response.data.contPic) {
      if(response.data.contPic instanceof Array) {

      } else {
        response.data.contPic = response.data.contPic.split(',')
      }
    }
    viewOpen.value = true;
  });
}
function handleSignTime() {
  if (form.value.contSignTime > form.value.contStartTime) {
    ElMessage.error('签约时间不能大于签约起止中的开始时间哦！')
  }
}
function handleContTimeChange(value) {
  if (value[0] < form.value.contSignTime) {
    ElMessage.error('签约起止中的开始时间不能小于签约时间哦！')
  }
  if (value && value.length === 2) {
    form.value.contStartTime = value[0];
    form.value.contEndTime = value[1];

    const startDate = new Date(value[0]);
    const endDate = new Date(value[1]);

    const MS_PER_MONTH = 1000 * 60 * 60 * 24 * 30;

    const timeDifference = endDate - startDate;
    const monthsDifference = timeDifference / MS_PER_MONTH;

    // if (monthsDifference >= 12) {
    //   const years = Math.floor(monthsDifference / 12);
    //   const remainingMonths = Math.floor(monthsDifference % 12);
    //
    //   if (remainingMonths > 0) {
    //     form.value.contractYears = `${years}年${remainingMonths}个月`;
    //   } else {
    //     form.value.contractYears = `${years}年`;
    //   }
    // } else {
    form.value.contLimit = `${Math.floor(monthsDifference)}个月`;
    // }
  }
}

onActivated(() => {
  getList();
})

getList();
</script>
